<?php

namespace App\Admin\Controllers;

use App\Models\SupplierGoods;

use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use Illuminate\Http\Request;


class supplierGoodsController extends Controller
{
    use ModelForm;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header('采购调价单');
            $content->description('');

            $content->body($this->grid());
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header('采购调价单');
            $content->description('');

            $content->body($this->editForm()->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header('采购调价单');
            $content->description('');

            $content->body($this->createForm());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(supplierGoods::class, function (Grid $grid) {
            $grid->model()->select(
                'sku.name as sku_name',
                'supplier.name as supplier_name',
                'supplier_goods_price_bill.*')

            ->join('sku','supplier_goods_price_bill.sku_id','=','sku.id')
            ->join('supplier','supplier.id','=','supplier_goods_price_bill.supplier_id')
            ->orderBy('supplier_goods_price_bill.created_at', 'desc');

            $grid->id("采购单编号");
            $grid->sku_name('SKU名称');
            $grid->supplier_name('供应商');
            $grid->cycle('采购周期');
            $grid->price('价格')->display(function($v){return round($v,2);});
            //$grid->status('采购价状态');
            //$grid->created_at('创建时间');
            //$grid->updated_at('更新时间');
            //$grid->remark('备注');
            // $grid->filter(function($filter){

            // });
            // $grid->actions(function ($actions) {
            //     $actions->disableEdit();
            // // $actions->disableDelete();
            // });

            $grid->actions(function ($actions) {
                    $actions->disableDelete();//禁用编辑
                    //$actions->disableEdit();//禁用删除
                });

            $grid->filter(function($filter){
                // 去掉默认的id过滤器
                $filter->disableIdFilter();

                $filter->where(function ($query) {
                    $query->where('supplier_goods_price_bill.id', 'like', "%{$this->input}%");
                }, '采购单编号');

                $filter->where(function ($query) {
                    $query->where('sku.name', 'like', "%{$this->input}%");
                }, 'SKU名称');

                $filter->where(function ($query) {
                    $query->where('supplier.name', 'like', "%{$this->input}%");
                }, '供应商名称');
            });

        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function editForm(){
        return Admin::form(supplierGoods::class, function (Form $form) {
            $skus= \DB::table('sku')->pluck('name','id');
            $suppliers = \DB::table('supplier')->pluck('name','id');
            $form->select('sku_id', 'sku')->options($skus);
            $form->number('cycle', '采购周期');
            $form->select('supplier_id', '供应商名称')->options($suppliers);
            $form->currency('price', '价格')->symbol(' ');
            $form->textarea('remark', '供应商商品描述');
            $form->select('status', '商品状态')->options(['有效','无效']);
        });
    }

    protected function createForm()
    {
        return Admin::form(supplierGoods::class, function (Form $form) {
            $form->setAction('mySubmit');
            $form->hasMany('fakeModel', function (Form\NestedForm $form) {
                $skus= \DB::table('sku')->pluck('name','id');
                $suppliers = \DB::table('supplier')->pluck('name','id');
                $form->select('sku_id', 'sku')->options($skus)->help('未填写sku的组将被忽略');
                $form->number('cycle', '采购周期');
                $form->select('supplier_id', '供应商名称')->options($suppliers);
                $form->currency('price', '价格')->symbol(' ');
                $form->textarea('remark', '供应商商品描述');
                // $form->hasMany('fakeModel', function (Form\NestedForm $form) {
                //     $form->text('price', '价格');
                // });
            });
        });
    }

    public function mySubmit(Request $req){
        // $data = Input::all();
        // if ($validationMessages = $form->validationMessages($data)) {
        //     return back()->withInput()->withErrors($validationMessages);
        // }
        $id = \DB::table('id_model')->where('common_key','supplier_goods_price_bill_id')->sharedLock()->value('common_value');
        \DB::table('id_model')->where('common_key','supplier_goods_price_bill_id')->increment('common_value',1);
        $arrs = [];
        $i = 1;
        if(!$req['fakeModel']){
            admin_toastr('没有任何调价','error');
            return back()->withInput();
        }
        foreach($req['fakeModel'] as $item){
            if(!$item['sku_id']){
                continue;
            }
            if(!$item['price']){
                admin_toastr('调价价格存在空值','error');
                return back()->withInput();
            }
            if($item['cycle']<1){
                admin_toastr('采购周期至少大于0','error');
                return back()->withInput();
            }
            if(!$item['supplier_id']){
                admin_toastr('供应商存在空值','error');
                return back()->withInput();
            }
            $id = "S".date('Ymd').$id.'-'.str_pad($i,4,"0",STR_PAD_LEFT);
            $arr['sku_id'] = $item['sku_id'];
            $arr['cycle'] = $item['cycle'];
            $arr['id'] = $id;
            $arr['supplier_id'] = $item['supplier_id'];
            $arr['price'] = $item['price'];
            $arr['remark'] = $item['remark'];
            $arr['created_at'] = date("Y-m-d H:i:s");
            array_push($arrs, $arr);
            $i++;
        }
        if (!$arrs) {
            admin_toastr('没有任何调价','error');
            return back()->withInput();
        }
        \DB::table('supplier_goods_price_bill')->insert($arrs);

        admin_toastr(trans('admin.save_succeeded'));
        $url = route('supplierGoods.index');
        return redirect($url);
    }
}